package com.streetsmart.test;
/**
 *  text to speech (tts)
 */
import java.util.Locale;

import com.streetsmart.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SpeechActivity extends Activity implements OnInitListener {

	private static final int MY_DATA_CHECK_CODE = 0;
	private TextToSpeech tts;


	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.speechsynthesis);
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
	}
	
	protected void onActivityResult(
	    int requestCode, int resultCode, Intent data) {
	    if (requestCode == MY_DATA_CHECK_CODE) {
	        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
	            // success, create the TTS instance
	            tts = new TextToSpeech(this, this);
	        } else {
	            // missing data, install it
	            Intent installIntent = new Intent();
	            installIntent.setAction(
	                TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
	            startActivity(installIntent);
	        }
	    }
	}
	
	public void speak(View v){
		EditText input = (EditText) findViewById(R.id.text);
		tts.speak(input.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
		input.setText("");
	}

	public void onInit(int status) {
		// TODO Auto-generated method stub
		Button b = (Button) findViewById(R.id.speak);
		b.setVisibility(View.VISIBLE);
		tts.setLanguage(Locale.US);
	}
	
	public void onDestroy(Bundle bundle){
		if(tts != null) {
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
		//TODO this is leaking memory. Need to check why.
	}
}
